package service;

import hibernate.IDao;

import java.util.List;

import models.Dict;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import cache.Cache;
import config.Constant;

@Service
public class DictService implements IDictService{
	
	@Autowired
	@Qualifier("commonDAO")
	private IDao dao;
	
	@SuppressWarnings("unchecked")
	public void refeshDictCache() {
		List<Dict> list = dao.findAll("from Dict where (disabled is null or disabled=?) and subDictCount>0 ",Constant.FALSE);
		for(Dict dict : list){
			Cache<String, String> cache = new Cache<String, String>();
			List<Dict> children = dao.findAll("from Dict where (disabled is null or disabled=?) and parent=?",Constant.FALSE,dict);
			for(Dict child:children){
				cache.put(child.getCode(), child.getName());
			}
			children = null;
			Constant.dictCache.put(dict.getCode(),cache);
		}
		list = null;
	}
	
	@SuppressWarnings("unchecked")
	public void refeshDictCache(String dictCode) {
		
		Cache<String, String> cache = new Cache<String, String>();
		List<Dict> children = dao.findAll("from Dict where parent.code = ?",dictCode);
		for(Dict child:children){
			cache.put(child.getCode() + " " + child.getName(), child.getName());
		}
		Constant.dictCache.put(dictCode,cache);
	}
	
	@SuppressWarnings("unchecked")
	public List<Dict> getByListCode(String dictCode){
		List<Dict> children = dao.findAll("from Dict d where d.parent.code = ? and d.disabled=? order by d.position asc",dictCode,Constant.FALSE);
		return children;
	}

	public IDao getDao() {
		return dao;
	}

	public void setDao(IDao dao) {
		this.dao = dao;
	}
}
